const { DataTypes, Model } = require('sequelize');
const sequelize = require('../db/index.js');
class Admin extends Model {}


Admin.init({
    username: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: true
    },
    password: {
        type: DataTypes.STRING,
        allowNull: false
    },
    email: {
        type: DataTypes.STRING,
        allowNull: true,
    },
}, {
    sequelize,
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    deletedAt: 'deleted_at',
    paranoid: true,
    defaultScope: {
        order: [['created_at', 'DESC']], // 设置默认排序
    },
});

const bcrypt = require('bcryptjs');

// 同步表后默认添加一个管理员
Admin.sync().then(async () => {
    try{
        let password =  '123456';
        let username = 'admin';
        let cryptedPassword = await bcrypt.hash(password, 10)
        let { id } = await Admin.create({
            username,
            password: cryptedPassword
        });
        if(id > 0){
            console.log(`添加默认管理员成功: username: ${username} password: ${password}`);
        }
    }catch(err){
        if(err.name !== 'SequelizeUniqueConstraintError'){
            console.log(err, '添加默认管理员失败');
        }
    }
});

module.exports = Admin;